package main

import (
	"fmt"
	"io"
	"log"
	"net"
	"runtime"
	_ "studygo/init"
	"sync"
	"time"
)

type Server struct {
	Ip   string
	Port int

	//onlineUser 在线用户的列表
	OnlineMap map[string]*User
	mapLock   sync.RWMutex
	//消息广播的 channel
	Message chan string
}

// NewServer 创建一个Server的接口
func NewServer(ip string, port int) *Server {
	server := &Server{
		Ip:        ip,
		Port:      port,
		OnlineMap: make(map[string]*User),
		Message:   make(chan string),
	}
	return server
}

// 监听Message广播消息的channel，一旦有消息就发送给全部的在线User
func (this *Server) ListenMessager() {
	for {
		msg := <-this.Message

		//将msg发送给全部的在线user
		this.mapLock.Lock()
		for _, cli := range this.OnlineMap {
			cli.C <- msg
		}
		this.mapLock.Unlock()
	}
}

//BroadCast 广播消息 user 发起用户user。
func (this *Server) BroadCast(user *User, msg string) {
	sendMsg := "[" + user.Addr + "]" + user.Name + ":" + msg
	this.Message <- sendMsg
}

// Handler 当前连接的业务
func (this *Server) Handler(conn net.Conn) {
	log.Println("上线用户:", conn.RemoteAddr())
	user := NewUser(conn, this)
	user.Online()

	//鉴听用户是否活跃
	isLive := make(chan bool)
	//接受客服端发送的消息
	go func() {
		buf := make([]byte, 4096)
		for {
			n, err := conn.Read(buf)
			if n == 0 {
				user.Offline()
				return
			}
			if err != nil && err != io.EOF {
				log.Println("Conn read err:", err)
				return
			}
			//提取用户消息出去\n
			user.DoMessage(string(buf[:n-1]))
			//用户的任意消息，代表当前用户是活跃的
			isLive <- true
		}
	}()
	//当前handler阻塞
	for {
		select {
		case <-isLive:
			//当前用户是活跃的，不做任何处理，为了激活select，更新下面的定时器
		case <-time.After(time.Hour * 200):
			//已经超时，将当前用户强制关闭
			user.SendMsg("超时被踢出")
			close(user.C)
			conn.Close()

			//或者使用return 退出
			runtime.Goexit()
		}
	}
	//select {}空select能阻塞 程序
}

// Start 启动服务器的接口
func (this *Server) Start() {
	//socket listen
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", this.Ip, this.Port))
	if err != nil {
		log.Println("net.Listen err:", err)
		return
	}
	defer func() {
		_ = listen.Close()
	}()

	//启动监听message 的goroutine
	go this.ListenMessager()
	for {
		//accept
		conn, err := listen.Accept()
		if err != nil {
			log.Println("listener accept err:", err)
			continue
		}
		//do handler
		go this.Handler(conn)
	}
}
